/*
 * HalSocket.cpp
 *
 *  Created on: 06-11-2011
 *      Author: cristian
 */

#include "HalSocket.h"

HalSocket::HalSocket() {
	this->logger = new Logger;
	this->setIsServer(false);
}

HalSocket::~HalSocket() {
	delete logger;
}

void HalSocket::closeSock() {
	Socket::closeSock();
}

void HalSocket::server(int port) {
	this->setIsServer(true);

	if (!Socket::create()) {
		throw WorkerSpaceException("Could not create server socket.");
	}

	if (!Socket::bind(port)) {
		throw WorkerSpaceException("Could not bind to port.");
	}

	if (!Socket::listen()) {
		throw WorkerSpaceException("Could not listen to socket.");
	}
}

void HalSocket::client(std::string host, int port) {

	if (!Socket::create()) {
		throw WorkerSpaceException("Could not create client socket.");
	}

	if (!Socket::connect(host, port)) {
		throw WorkerSpaceException("Could not bind to port.");
	}

}

const HalSocket& HalSocket::operator <<(const std::string& s) const {
	if (!Socket::send(s)) {
		throw WorkerSpaceException("Could not write to socket.");
	}

	return *this;

}

const HalSocket& HalSocket::operator >>(std::string& s) const {
	if (!Socket::recv(s)) {
		throw WorkerSpaceException("Could not read from socket.");
	}

	return *this;
}

bool HalSocket::isIsServer() const {
	return this->isServer;
}

void HalSocket::setIsServer(bool isServer) {
	this->isServer = isServer;
}

HalSocket::HalSocket(bool isServer, bool isClient) {
	this->setIsServer(isServer);
}

void HalSocket::accept(HalSocket& sock) {

	if (!Socket::accept(sock)) {
		throw WorkerSpaceException(" Problema acceptando conexion en el socket");
	} else {
		HAL_TRACE_CORE(logger, "aceptando conexion desde socket ");

	}
}



string *HalSocket::getIp(HalSocket *socketaddr)
{

	socklen_t peer_len;

	   peer_len = sizeof(struct sockaddr_in);

	   if (getpeername(socketaddr->m_sock,(struct sockaddr *) &(socketaddr->m_addr), &peer_len) == -1) {
	      perror("getpeername() failed");
	      return NULL;
	   }
	   const char* host = inet_ntoa(socketaddr->m_addr.sin_addr);
	   string* host2 = new string(host);

	   // printf("Peer's IP address is: %s\n", );
	//   printf("Peer's port is: %d\n", (int) ntohs(socketaddr->m_addr.sin_port));

	   return host2;
}




